package com.apimarket.util.net;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.entity.StringEntity;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.Map;

/**
 * 处理不同类型请求的抽象基类
 */
public abstract class NetContext {
    private String url;

    private Map<String, Object> params;

    protected static final Logger logger = LogManager.getLogger(NetContext.class);

    //读取HttpEntity流实体中的内容
    public static String getJsonStr(HttpEntity entity) throws IOException {
        StringBuilder jsonStr = new StringBuilder();
        InputStream in = entity.getContent();
        byte[] buffer = new byte[512];
        int len = -1;
        while ((len = in.read(buffer)) != -1) {
            jsonStr.append(new String(buffer, 0, len));
        }
        return jsonStr.toString();
    }

    //这个方法主要用于设置请求的参数
    protected void setJsonStyle(HttpEntityEnclosingRequest request) throws JsonProcessingException, UnsupportedEncodingException {
        request.setHeader("Content-Type", "application/json");
        Map<String, Object> tmp = getParams();
        if (tmp != null && tmp.keySet().size() != 0) {
            //将Object转为json字符串
            String jsonStr = new ObjectMapper().writeValueAsString(tmp);
            logger.info(jsonStr);
            //httpclient在实现带采纳数的post请求时候可以用StringEntity作为参数传递
            StringEntity entity = new StringEntity(jsonStr);
            entity.setContentType("text/json");
            request.setEntity(entity);
        }
    }


    public NetContext(String url, Map<String, Object> params) {
        this.url = url;
        this.params = params;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Map<String, Object> getParams() {
        return params;
    }

    public void setParams(Map<String, Object> params) {
        this.params = params;
    }

    public abstract JsonNode getResultJson() throws IOException, URISyntaxException;
}
